from django.shortcuts import render

# Create your views here.


from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework.decorators import action
from .models import User
from utils.respons import APIRespons
from django.contrib.auth import authenticate

from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

# @功能：class Login_Register
# @说明：登录注册
# @作者：xiao
# @日期：2021/09/24
class Login_Register(ViewSet):

    @action(methods=["POST"],detail=False)
    def reg(self,request):
        username = request.data.get("username")
        password = request.data.get("password")
        user = User.objects.filter(username = username)
        if user:
            return APIRespons({'status':600,'msg':'用户名已存在'})
        else:
            User.objects.create_user(username=username,password=password)
            return APIRespons({'status':811,'msg':'注册成功'})

    @action(methods=["POST"],detail=False)
    def login(self,request):
        username = request.data.get("username")
        password = request.data.get("password")

        user=authenticate(username=username,password=password)
        if user:
            # 签发token
            payload = jwt_payload_handler(request.user)

            token=jwt_encode_handler(payload)

            return APIRespons({'status':833,'msg':'登录成功','token':token})
        return APIRespons({'status':611,'msg':'用户名密码错误'})